package seotools.positions.agg;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class PositionsAggregator {
    private static final String DATE_FORMAT = "dd-MM-yyyy-HH-mm";
    private static final String OUT_DATE_FORMAT = "dd.MM.yy HH:mm";
    //    public static final String PROJECT = "bikemotors.ru";
    public static final String PROJECT = "extramobi";
//    public static final String PROJECT = "extramobi-nokia";
//    public static final String PROJECT = "extramobi-se";
//    public static final String PROJECT = "extramobi-samsung";
    //    public static final String PROJECT = "fgarden";
//    public static final String PROJECT = "vitmar-wedding";
    static SimpleDateFormat inFormat = new SimpleDateFormat(DATE_FORMAT);
    static SimpleDateFormat outFormat = new SimpleDateFormat(OUT_DATE_FORMAT);

    public static void main(String[] args) throws IOException {
        File projectDir = new File("projects\\" + PROJECT);
        aggregate(projectDir);
    }

    public static void aggregate(File projectDir) throws IOException {
        Map<Date, List<Position>> positionsByDate = new HashMap<Date, List<Position>>();
        List<Phrase> phrases = new ArrayList<Phrase>();
        List<Date> dates = new ArrayList<Date>();
        File[] files = projectDir.listFiles();
        File outPath = null;
        for (File file : files) {
            if (file.isDirectory()) {
                aggregate(file);
            } else {
                try {
                    String dateString = file.getName();
                    Date date = inFormat.parse(dateString);
                    List<Position> positionsList = parsePositions(file);
                    if (phrases.size() == 0) {
                        phrases = parsePhrases(file);
                        dates = parseDates(file.getParentFile());
                        Collections.sort(dates);
                    }
                    positionsByDate.put(date, positionsList);
                    System.out.println(file.getParent() + ":" + outFormat.format(date));
                    String fileName = file.getParentFile().getName();
                    outPath = new File(file.getParentFile(), fileName + ".html");
                } catch (ParseException e) {
                    // not a stat file
                }
            }
        }
        if (outPath == null) {
            return;
        }
        PrintStream out = new PrintStream(new FileOutputStream(outPath));
        StringBuffer html = new StringBuffer("<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><body><table border=\"solid 1px\"><tr><td></td>");
        for (Date snapshotDate : dates) {
            html.append("<td colspan=\"2\" style=\"font-weight:bold\">").append(outFormat.format(snapshotDate)).append("</td>");
        }
        for (Phrase phrase : phrases) {
            html.append("<tr><td>").append(phrase.phrase).append("</td>");
            List<Position> prevPositions = null;
            for (Date snapshotDate : dates) {
                List<Position> positions = positionsByDate.get(snapshotDate);
                Position pos = new Position();
                pos.phrase = phrase.phrase;
                int index = positions.indexOf(pos);
                if (index == -1) {
                    html.append("<td></td><td></td>");
                    continue;
                }
                pos = positions.get(index);
                String yandexColor = "white";
                String googleColor = "white";
                String yandexBorderColor = "white";
                String googleBorderColor = "white";
                if (prevPositions != null) {
                    Position prevPos = prevPositions.get(index);
                    yandexColor = pos.yandexPosition > prevPos.yandexPosition ? "#ff3300" : "#00CC00";
                    yandexColor = pos.yandexPosition == prevPos.yandexPosition ? "white" : yandexColor;
                    googleColor = pos.googlePosition > prevPos.googlePosition ? "#ff3300" : "#00CC00";
                    googleColor = pos.googlePosition == prevPos.googlePosition ? "white" : googleColor;
                    yandexBorderColor = pos.yandexPosition <= 10 ? "#ffff00" : "white";
                    googleBorderColor = pos.googlePosition <= 10 ? "#ffff00" : "white";
                }
                String yandexWeight = yandexColor.equals("white") ? "bormal" : "bold";
                String googleWeight = googleColor.equals("white") ? "bormal" : "bold";
                String title = phrase.phrase + ":" + phrase.requestsCount;
                html.append("<td title=\"").append(title).append("\" style=\"border-color:" + yandexBorderColor + ";font-weight:").append(yandexWeight).append("; text-align:center; background-color: ").append(yandexColor).append("\">").append(pos.yandexPosition).
                        append("</td><td title=\"").append(title).append("\" style=\"border-color:" + googleBorderColor + ";font-weight:").append(googleWeight).append("; text-align:center; background-color: ").append(googleColor).append("\">").append(pos.googlePosition).append("</td>");
                prevPositions = positions;
            }
            html.append("</tr>");
        }
        html.append("</tr>");
        html.append("</table></body></html>");
        out.println(html);
        out.close();
    }

    private static List<Date> parseDates(File parentFile) {
        List<Date> datesList = new ArrayList<Date>();
        String[] files = parentFile.list();
        for (String file : files) {
            try {
                Date date = inFormat.parse(file);
                datesList.add(date);
            } catch (ParseException e) {
                continue;
            }
        }
        return datesList;
    }

    private static List<Phrase> parsePhrases(File file) throws IOException {
        String requestsFile = file.getParentFile().getPath() + "\\" + file.getParentFile().getName() + ".txt";
        BufferedReader reader = new BufferedReader(new FileReader(requestsFile));
        String line;
        List<Phrase> phrases = new ArrayList<Phrase>();
        while ((line = reader.readLine()) != null) {
            String[] fields = line.split(",");
            Phrase phrase = new Phrase();
            if (fields.length != 2) {
                continue;
            }
            phrase.phrase = fields[0];
            phrase.requestsCount = Integer.parseInt(fields[1]);
            phrases.add(phrase);
        }
        reader.close();
        return phrases;
    }

    private static List<Position> parsePositions(File file) throws IOException {
        List<Position> positionsList = new ArrayList<Position>();
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.length() == 0) continue;
            Position pos = new Position();
            String[] fields = line.split(",");
            pos.phrase = fields[0];
            pos.yandexPosition = Integer.parseInt(fields[2]);
            if (fields.length <= 3) {
                pos.googlePosition = 101;
            } else {
                pos.googlePosition = Integer.parseInt(fields[3]);
            }
            positionsList.add(pos);
        }
        return positionsList;
    }

    static class Position {
        String phrase;
        int yandexPosition;
        int googlePosition;

        @Override
        public String toString() {
            return "<td>" + yandexPosition + "</td><td>" + googlePosition + "</td>";
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            Position position = (Position) o;

            if (phrase != null ? !phrase.equals(position.phrase) : position.phrase != null) return false;

            return true;
        }

        @Override
        public int hashCode() {
            return phrase != null ? phrase.hashCode() : 0;
        }
    }

    static class Phrase {
        String phrase;
        int requestsCount;
    }
}
